package com.heiketu.contols;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
public class HandlerControl {

    @PostMapping(value = "/success",produces = "text/plain;charset=utf-8" )
    public String login(HttpServletRequest request){

        /**
         * spring security框架，会将认证后的用户信息存放在SecurityContext上下文环境中
         */
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal(); // 获得用户主体(即用户对象UserDetail)
        if(Objects.isNull(principal)){
            throw new RuntimeException("登录错误");
        }

        StringBuilder sb = new StringBuilder();
        sb.append("登录成功");
        // 一般情况下，主体即UserDetailService返回的UserDetails对象
        if(principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails)principal;
            sb.append(userDetails.getUsername());
        }

        return sb.toString();
    }

    // p1资源
    @PreAuthorize("hasAuthority('p1')")
    @GetMapping(value = "/r/p1",produces = "text/plain;charset=utf-8")
    public String p1(){
        return "访问资源p1";
    }

    // p2资源
    @PreAuthorize("hasAuthority('p2')")
    @GetMapping(value = "/r/p2",produces = "text/plain;charset=utf-8")
    public String p2(){
        return "访问资源p2";
    }

}
